/*
 * Copyright (c) 2011, Andrew Cole
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

package net.andycole.xmiparser.parser;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.adobe.ac.pmd.parser.exceptions.TokenException;

import net.andycole.xmiparser.transfer.TransferClass;

/**
 * Parses mxml files.
 * @author Andrew Cole
 */
public class MXMLFileParser extends ASFileParser
{

   private Logger LOG = Logger.getLogger(MXMLFileParser.class);

   public MXMLFileParser()
   {
      
   }

   @Override
   public TransferClass parse(final String filePath,
                              final String packageName,
                              final String[] lines ) throws TokenException
   {
      boolean validate = false;

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setValidating(validate);
      dbf.setNamespaceAware(true);
      dbf.setIgnoringElementContentWhitespace(true);

      // Parse the input to produce a parse tree with its root
      // in the form of a Document object
      FileInputStream inStream = null;

      try
      {
         File sourceFile = new File(filePath);
         String className = sourceFile.getName();
         if (className.indexOf(".") > -1)
            className = className.substring(0, className.indexOf("."));
         _classInfo.setClassName(className);

         DocumentBuilder builder = dbf.newDocumentBuilder();
         inStream = new FileInputStream(sourceFile);
         InputSource is = new InputSource(inStream);
         Document doc = builder.parse(is);
         _parseDoc(doc);
         super.parse(filePath, packageName, lines);
      }
      catch (SAXException e)
      {
//         System.err.println(e);
         LOG.warn(e);
      }
      catch (ParserConfigurationException e)
      {
//         System.err.println(e);
         LOG.warn(e);
      }
      catch (IOException e)
      {
//        System.err.println(e);
        LOG.warn(e);
      }
      finally
      {
         try{
            if (inStream != null)
               inStream.close();
         }
         catch(IOException closeEx)
         {
//            System.err.println("Could not close file stream "+closeEx);
            LOG.warn("Could not close file stream "+closeEx);
         }
      }
      return _classInfo;
   }

   private void _parseDoc(Document doc)
   {
      Element docElem = doc.getDocumentElement();
      //String nodeName = docElem.getNodeName();

      String extendsName = docElem.getAttribute("extends");
      extendsName = getQualifiedType(extendsName);
      _classInfo.setExtends(extendsName);
      String implStr = docElem.getAttribute("implements");
      implStr = implStr.trim();
      StringTokenizer strTok = new StringTokenizer(implStr, ",");
      while (strTok.hasMoreTokens())
      {
         String implementsType = strTok.nextToken();
         implementsType = getQualifiedType(implementsType);
         _classInfo.addImplement(implementsType);
      }
   }
}
